/******************************************************************************

    Copyright (C) 2006-2011 Alessio Stalla (alessiostalla@gmail.com)

    This file is part of PrettyProlog.

    PrettyProlog is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    PrettyProlog is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PrettyProlog; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

    See the file COPYING for further details.

 *****************************************************************************/

package prettyprolog.datatypes;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * A Symbol is a name for a Variable or a Callable. Symbols have identity, that
 * is, it's possible to have two symbols which are the same name (have the same
 * printed representation) but are treated by the system as different objects.
 * Usually you won't create symbols directly; use the Namespace class
 * instead.
 */
public class Symbol implements Serializable {

	private static final long serialVersionUID = 1L;	
	
	protected String name;
	protected boolean infix;
	protected boolean terminating;
	protected Namespace namespace;

	/** Creates a new Symbol with print name <code>s</code>. */
	public Symbol(String s, Namespace namespace) {
		this.name = s;
		this.namespace = namespace;
	}

	/** @return the printed representation of this Symbol. */
	public String getName() {
		return name;
	}
	
	public void setInfix(boolean infix) {
		this.infix = infix;
		Namespace.infix(this, infix);
	}
	
	public boolean isInfix() {
		return infix;
	}
	
	public void setTerminating(boolean terminating) {
		if(!isInfix()) {
			throw new IllegalStateException(this + " is not infix and cannot be declared terminating");
		}
		this.terminating = terminating;
	}
	
	public boolean isTerminating() {
		return terminating;
	}
	
	public Namespace getNamespace() {
		return namespace;
	}

	@Override
	public String toString() {
	    Namespace currentNamespace = Namespace.current();
	    if(currentNamespace != namespace && namespace != null) {
	        return namespace.getName() + ":" + name;
	    } else {
	        return name;
	    }
	}
	
	private Object readResolve() throws ObjectStreamException {
		if(namespace != null) {
			Symbol sym = namespace.intern(name);
			sym.setInfix(infix);
			return sym;
		} else {
			return this;
		}
	}
	
}